package com.king.student.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.king.student.entity.Clazz;
import com.king.student.sql.SqlUtility;

public class ClassDao {

	//添加一个班级
	public static boolean addClass(Clazz clazz){
		try {
			String sql = "insert into class(classID,className)"
					+ " values(?,?)";
			PreparedStatement ps = SqlUtility.getConnection().prepareStatement(sql);
			ps.setString(1, clazz.getClassID());
			ps.setString(2, clazz.getClassName());
			ps.execute();
			return true;
		} catch (SQLException e) {
		}
		return false;
	}
	
	//删除班级
	public static boolean delClass(String classID){
		try {
			String sql = "delete from class where classID=?";
			PreparedStatement ps = SqlUtility.getConnection().prepareStatement(sql);
			ps.setString(1, classID);
			ps.execute();
			return true;
		} catch (SQLException e) {
		}
		return false;
	}
	
	//更新班级数据
	public static boolean updateClass(Clazz clazz){
		try {
			String sql = "update class set className=? where classID=?";
			PreparedStatement ps = SqlUtility.getConnection().prepareStatement(sql);
			ps.setString(1, clazz.getClassName());
			ps.setString(2, clazz.getClassID());
			ps.execute();
			return true;
		} catch (SQLException e) {
		}
		return false;
	}
	
	//根据班级编号查询班级
	public static Clazz getClassByClassID(String classID){
		try {
			String sql = "select * from class where classID=?";
			PreparedStatement ps = SqlUtility.getConnection().prepareStatement(sql);
			ps.setString(1, classID);
			ResultSet rs = ps.executeQuery();
			Clazz clazz = new Clazz();
			rs.next();
			clazz.setClassID(rs.getString("classID"));
			clazz.setClassName(rs.getString("className"));
			return clazz;
		} catch (SQLException e) {
		}
		return null;
	}
	
	//查询所有班级
	public static List<Clazz> getAllClass(){
		try {
			String sql = "select * from class";
			PreparedStatement ps = SqlUtility.getConnection().prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			
			List<Clazz> list = new ArrayList<>();
			while(rs.next()){
				Clazz clazz = new Clazz();
				clazz.setClassID(rs.getString("classID"));
				clazz.setClassName(rs.getString("className"));
				list.add(clazz);
			}
			
			return list;
		} catch (SQLException e) {
		}
		return Collections.emptyList();
	}
	
}
